package modelo;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import beans.MozoBean;
import beans.PerfilBean;
import entities.MozoEntity;
import entities.PerfilEntity;
import hbt.AbstractHibernateManager;


public class MozoDao extends AbstractHibernateManager {
	
	private static MozoDao instancia = null;
	
	public static MozoDao getInstancia() {
		if(instancia == null) {
			instancia = new MozoDao();
		}
		return instancia;
	}

	public void save (MozoEntity mozo){
		Session s = null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.persist(mozo);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[mozo PERSISTED ON TABLE personal]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
	}
	
	
	public void guardar (MozoEntity mozo){
		Session s = null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.save(mozo);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[mozo SAVED ON TABLE personal]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
	}

	
	public void merge (MozoEntity mozo){
		Session s = null;
		try {
			s=getNewSession();
			s.beginTransaction();
			s.merge(mozo);
			s.flush();
			s.getTransaction().commit();
			System.out.println("[mozo MERGED ON TABLE personal]::OK");
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
	}
	
	
	
	public List<MozoEntity> obtenerMozos() {
		@SuppressWarnings("unchecked")
		List<MozoEntity> mozos = (List<MozoEntity>) findAll("MozoEntity");
		return mozos;
	}
	

	public MozoEntity obtenerMozo(Integer idMozo) {
		Session s = null;
		MozoEntity mozo = new MozoEntity();
		
		try {
			s = getNewSession();
			mozo = (MozoEntity) s.createQuery("FROM MozoEntity m " +
									  "WHERE m.legajo = :idMozo")
							  .setInteger("idMozo", idMozo)
							  .uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return mozo;	
	}
	
	public List<MozoEntity> obtenerMozosPorSector(Integer idSector)
	{
		Session s = null;
		List<MozoEntity> mozos = new ArrayList<MozoEntity>();
		
		//ToDo: armar bien la query
		try {
			s = getNewSession();
			mozos =  s.createQuery("")
							  .setInteger("iSector", idSector)
							  .list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			closeSession(s);
		}
		return mozos;
	}

}
